<script setup>
import { computed, onMounted, reactive, ref, watchEffect } from 'vue';
import data from "@/untils/address/states.json"
const formLabelWidth = '100px'
//  import dayjs from "dayjs"
import { ElMessage } from 'element-plus'
// import { addclassinfo,updateClass } from '../../api/request';
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import axios from 'axios';
// import { addarea ,addschoolbasics,updateClass, updateschoolbasics} from '../../api/request';
import dayjs from 'dayjs';
import { Decrypt, Encrypt } from '../../untils/passjs/security';
import { getallocationadmin,getallocationdistributor,getallocationenduser,likeyuadmin,likeyudistributor,likeyuenduser,submitauthorize } from '../../api/api';
let formRef = ref(null)
let props = defineProps({
    dialogFormVisible: Boolean,
    formlist: Object,
    changeType: String,
    type: String,
    roleId: Number
})
let chuangData = ref([])
let topdata = ref({
    nickname: "",
    phone: "",
})
let total = ref(0)
let page = ref(1)
let pageSize = ref(10)
watchEffect(async () => {
    console.log(props.type);
    if (props.type == "admin") {
        let data = await getallocationadmin(2, props.roleId,page.value,pageSize.value)
        if (data.code == 200) {
            total.value = data.total
            chuangData.value = data.rows
        }
    } else if (props.type == 'distributor') {
        let data = await getallocationdistributor(2, props.roleId,page.value,pageSize.value)
        if (data.code == 200) {
            total.value = data.total
            chuangData.value = data.rows
        }
    } else if (props.type == 'enduer') {
        let data = await getallocationenduser(1, props.roleId,page.value,pageSize.value)
        if (data.code == 200) {
            total.value = data.total
            chuangData.value = data.rows
        }
    }
})
onMounted(async () => {

})
let emits = defineEmits(["close", 'update:formlist'])
function closedialog(formEl) {
    // // 再次点击清空inp的值
    if (!formEl) return
    // formEl.resetFields()
    // // // 向父组件发送自定义事件
    emits("close")
    userId.value = []
}
let closefun = ()=>{
    console.log("111");
     emits("close")
     userId.value = []
}
let switchFlag = (flag) => {
    return flag == 0 ? true : false;
}
const cancel =async () => {
    // open.value = false
    // resetForm()
    topdata.value = {
        nickname:"",
        phone:""    
    }
    if (props.type == "admin") {
        let data = await getallocationadmin(2, props.roleId)
        if (data.code == 200) {
            total.value = data.total
            chuangData.value = data.rows
        }
    } else if (props.type == 'distributor') {
        let data = await getallocationdistributor(2, props.roleId)
        if (data.code == 200) {
            total.value = data.total
            chuangData.value = data.rows
        }
    } else if (props.type == 'enduer') {
        let data = await getallocationenduser(1, props.roleId)
        if (data.code == 200) {
            total.value = data.total
            chuangData.value = data.rows
        }
    }
}


// 加载菜单树
const getMenuTree = () => {
    listMenu().then(response => {
        menuOptions.value = response.data
    })
}

// 树形选择器转换
const normalizer = node => {
    if (node.children && !node.children.length) {
        delete node.children
    }
    return {
        id: node.menuId,
        label: node.menuName,
        children: node.children
    }
}
async function searchlike(){
    console.log("模糊");
    console.log(topdata.value);
    
     if (props.type == "admin") {
        let data = await likeyuadmin(2, props.roleId,topdata.value.nickname,topdata.value.phone)
        if (data.code == 200) {
            total.value = data.total
            chuangData.value = data.rows
        }
    } else if (props.type == 'distributor') {
        let data = await likeyudistributor(2, props.roleId,topdata.value.nickname,topdata.value.phone)
        if (data.code == 200) {
            total.value = data.total
            chuangData.value = data.rows
        }
    } else if (props.type == 'enduer') {
        let data = await likeyuenduser(2, props.roleId,topdata.value.nickname,topdata.value.phone)
        if (data.code == 200) {
            total.value = data.total
            chuangData.value = data.rows
        }
    }
    
}
async function getCurrentPage(e) {
    console.log("获取当前页", e);
    page.value = e
    if (props.type == "admin") {
        let data = await getallocationadmin(2, props.roleId,e,pageSize.value)
        if (data.code == 200) {
            total.value = data.total
            chuangData.value = data.rows
        }
    } else if (props.type == 'distributor') {
        let data = await getallocationdistributor(2, props.roleId,e,pageSize.value)
        if (data.code == 200) {
            total.value = data.total
            chuangData.value = data.rows
        }
    } else if (props.type == 'enduer') {
        let data = await getallocationenduser(1, props.roleId,e,pageSize.value)
        if (data.code == 200) {
            total.value = data.total
            chuangData.value = data.rows
        }
    }
    // let res = await getAdmindatapage(e,pageSize.value)
    // console.log(res);
    //  if (res.code == 200) {
    //     tableData.value = res.rows
    // }
}

// 新增：用于存储选中的行
const selectedRows = ref([])
let userId = ref([])
function check(selection){
    // / selection 参数就是当前所有被选中的行数据数组
    selectedRows.value = selection
    console.log('当前选中的行:', selectedRows.value)
    selectedRows.value.forEach(item=>{
        userId.value.push(item.userId)
    })
    userId.value = [...new Set(userId.value)]
}
function getRowKeys(row) {
    return row.userId

}
const rowSelectChange = (selection, row) => {
    // 判断是否选中,选中ids增加，取消选中ids删除
    if (selection.filter(item => item.userId == row.userId).length >= 1) {
        userId.value.push(row.userId)
    } else {
        userId.value = userId.value.filter(item => item != row.userId)
    }
}
const handleSelectionChange = (selection) => {
    userId.value = selection.map((item) => item.userId);
}
async function submitauto(){
    selectedRows.value = []
    console.log(props.roleId);
    console.log(userId.value);
    if(userId.value.length == 0){
          emits("close")
        return;
       
    }
    let val = {
        roleId: props.roleId,
        userIds: userId.value,
        optType: 6
    }
    let res = await submitauthorize(val)
    console.log(res);
    if(res.code == 200){
        ElMessage.success(res.msg)
        
    }
   
    // emits("close")
}
</script>
<template>
    <div class="editclass">
        <el-dialog :model-value="dialogFormVisible" style="padding: 40px;width: 800px" title="select User" @close="closefun">
            <div class="one">
            </div>

            <div class="tab">
                <!-- @selection-change="check" -->
                <el-table stripe :data="chuangData"  @select="rowSelectChange" @selection-change="handleSelectionChange" :row-key="getRowKeys" style="width: 100%;" :fit="true" v-if="chuangData.length > 0">
                    
                    <el-table-column type="selection"  :reserve-selection="true" width="55" />
                    <el-table-column property="username" label="name" />
                    <el-table-column property="nickname" label="nickname" />
                    <el-table-column property="phone" label="cell-phone number" />
                    <el-table-column property="email" label="email" />
                    <el-table-column property="gender" label="gender">
                        <template #default="scope">
                            <span>{{ scope.row.gender == 1 ? 'male' : 'female' }}</span>
                        </template>
                    </el-table-column>

                    <el-table-column property="accountNonLocked" label="Lock status">
                        <template #default="scope">
                            <!-- <el-switch :modelValue="" active-text="enable"
                                inline-prompt inactive-text="disable"
                                @click="switchchange(scope.row.userId, scope.row.accountNonLocked)" class="el-switch">
                            </el-switch> -->
                            <span>{{ switchFlag(scope.row.accountNonLocked) ? 'open':'close' }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column property="enabled" label="Startup status">
                        <template #default="scope">
                            <!-- <el-switch :modelValue="switchFlag(scope.row.enabled)" active-text="enable" inline-prompt
                                inactive-text="disable"
                                @click="switchchangeenabled(scope.row.userId, scope.row.enabled)" class="el-switch">
                            </el-switch> -->
                            <span>{{ switchFlag(scope.row.enabled) ? 'open':'close'}}</span>
                        </template>
                    </el-table-column>

                </el-table>
                <div style="display: flex;justify-content: end;align-items: center; margin-top: 25px">
                    <el-pagination background layout="prev, pager, next" :page-count="Math.ceil(total / pageSize)"
                        style="text-align: end;" :current-page='page' @current-change="getCurrentPage" />
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitauto">sure</el-button>
                    <el-button @click="closefun">cansel</el-button>
                </div>
            </template>
        </el-dialog>

    </div>
</template>

<style lang="scss" scoped>
.one {
    display: flex;
}

.two-column-form .form-row {
    display: flex;
    justify-content: space-between;
}

.two-column-form .el-form-item {
    width: 48%;
}

.address-container {
    display: flex;
    align-items: center;
}

/* 调整表单标签宽度 */
.two-column-form :deep(.el-form-item__label) {
    width: 80px;
    text-align: right;
    padding-right: 12px;
}

/* 响应式设计 - 小屏幕时变为单列 */
@media (max-width: 768px) {
    .two-column-form .form-row {
        flex-direction: column;

        .el-form-item {
            width: 100%;
        }
    }

    .address-container {
        flex-direction: column;
        align-items: flex-start;

        .el-select {
            width: 100% !important;
            margin-right: 0 !important;
            margin-bottom: 10px;
        }
    }
}
</style>